package com.hmall.search.web.interceptor;

import com.hmall.domain.utils.ThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 搜索商品拦截器，用户获取请求头
 *
 * @Author XiaoJiangShi
 * @Date 2022/8/11 18:15
 * @Blog blog.XiaoJiangShi.net/996.mba
 * @Description: 搜索商品拦截器，用户获取请求头
 */
@Component
public class GetHeaderHandlerInterceptor implements HandlerInterceptor {
    /**
     * 原始方法执行前执行
     *
     * @param request  请求
     * @param response 响应
     * @param handler  方法
     * @return 返回值，是否执行后续方法
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String id = request.getHeader("authorization");
        if (StringUtils.isNotBlank(id)) {
            ThreadLocalUtil.setId(id);
            return true;
        }
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=uft-8");
        response.getWriter().write("{\"message\":\"非法登录，没有权限！\"}");
        return false;

    }

    /**
     * 渲染数据后执行
     *
     * @param request  请求
     * @param response 响应
     * @param handler  方法
     * @param ex       异常
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}

